<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="sepBread">
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-row type="flex" align="middle">
      <el-col :span="2">
        <el-select
          v-model="province"
          clearable
          placeholder="请选择省份"
          class="selectData"
          @change="changeProvinceValue($event)"
        >
          <el-option
            v-for="item in provinceList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-select
          v-model="city"
          clearable
          placeholder="请选择城市"
          class="selectData"
        >
          <el-option
            v-for="item in cityList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-input
          v-model="orderNum"
          type="text"
          placeholder="请输入订单号"
          clearable
        />
      </el-col>
      <el-col :span="2">
        <el-select
          v-model="orderType"
          clearable
          placeholder="订单类型"
          class="selectData"
        >
          <el-option
            v-for="item in orderCateArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-select
          v-model="orderSource"
          clearable
          placeholder="订单来源"
          class="selectData"
        >
          <el-option
            v-for="item in orderSourceArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-select
          v-model="orderState"
          clearable
          placeholder="订单状态"
          class="selectData"
        >
          <el-option
            v-for="item in orderStateArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="dataTimeArr"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-ddTHH:mm:ssZ"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-col>
      <el-col :span="1">
        <el-button type="primary" class="searchBtn" @click="searchBtn"
          >搜索</el-button
        >
      </el-col>
    </el-row>
    <el-row class="secondDetail">
      <el-col :span="2">
        <el-button type="primary" class="addBtn" @click="addBtnn"
          >添加订单</el-button
        >
      </el-col>
      <el-col :span="2">
        <download-excel
          class="export-excel-wrapper"
          :data="tableData"
          name="订单管理表格.xls"
        >
          <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
          <el-button type="primary" @click="daochu">导出订单</el-button>

          <!-- 预览弹窗表格 -->
          <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
            <el-table :data="tableData" id="selectTable" height="380px">
                <el-table-column
                        prop="orderType"
                        label="订单类型"
                >
                </el-table-column>
                <el-table-column
                        prop="carownerName"
                        label="姓名"
                >
                </el-table-column>
               
                    <el-table-column
                            prop="cityName"
                            label="城市"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="orderOrigin"
                            label="订单来源"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="carNum"
                            label="车牌号"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="driverName"
                            label="接车司机"
                    >
                    
                </el-table-column>
                <el-table-column
                            prop="orderStatus"
                            label="订单状态"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="orderTime"
                            label="下单时间"
                    >
                    </el-table-column>
                      <el-table-column
                            prop="payStatus"
                            label="付款状态"
                    >
                    </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exportExcel">确定保存</el-button>
            </div>
        </el-dialog>



        </download-excel>
      </el-col>

      <el-col :span="2">
        <!-- <div>
          <div class="container">
            {{ "导入" }}
            <el-input type="file" accept=".xls,.xlsx" class="upload_file" @change="readExcel($event)" />
            <el-button type="primary" @click="importData('ruleForm')">确 定</el-button>
          </div>
        </div> -->

        <!-- :auto-upload="false" -->
        <el-upload
          action="#"
          :multiple="false"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :limit="1"
          :before-upload="handleBeforeUpload"
          :file-list="lists"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
          class="delBtn"
          @click="batchDelete(tableChecked)"
          >批量删除</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="tableData"
        scope="scope"
        tooltip-effect="dark"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange($event)"
      >
        <el-table-column type="selection" width="30"> </el-table-column>
        <el-table-column label="订单编号" prop="orderNum">
          <template slot-scope="scope">
            <div
              :style="{ color: 'blue' }"
              class="orderid"
              @click="orderDetailSee(scope.$index, scope.row)"
            >
              {{ scope.row.orderNum }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderType" label="订单类型"> </el-table-column>
        <el-table-column prop="carownerName" label="车主姓名" width="70">
        </el-table-column>
        <el-table-column prop="cityName" label="城市" width="60">
        </el-table-column>
        <el-table-column prop="orderOrigin" label="订单来源"> </el-table-column>
        <el-table-column prop="carNum" label="车牌号"> </el-table-column>
        <el-table-column prop="driverName" label="接车司机"> </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态"></el-table-column>
        <el-table-column prop="orderTime" label="下单时间"> </el-table-column>
        <el-table-column prop="payStatus" label="付款状态"> </el-table-column>
        <el-table-column label="操作">
          <template scope="scope" class="active">
            <el-button
              type="primary"
              @click="modifyBtn(scope.row)"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              type="danger"
              @click="deleteBtn(scope.$index, scope.row)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        :total="count"
        layout=" total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-row>
  </div>
</template>

<script>
import excel from "@/meimei/excel.js";

export default {
  data() {
    return {
      selectWindow:false,
      tableChecked: [],
      ids: [],
      upload_file: "",
      lists: [],
      orderStateArr: [
        {
          value: "待处理",
          label: "待处理",
        },
        {
          value: "已处理",
          label: "已处理",
        },
        {
          value: "订单关闭",
          label: "订单关闭",
        },
      ],

      orderSourceArr: [
        {
          value: "后台",
          label: "后台",
        },
        {
          value: "第三方",
          label: "第三方",
        },
      ],

      orderCateArr: [
        {
          value: "领标订单",
          label: "领标订单",
        },
        {
          value: "验车订单",
          label: "验车订单",
        },
        {
          value: "异地委托函",
          label: "异地委托函",
        },
        {
          value: "新车上牌",
          label: "新车上牌",
        },
      ],
      provinceList: [],
      loading: false,
      currentPage: 1,
      page: 1,
      pageSize: 10,
      //表示服务器当前的数据总数
      count: 0,
      index: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      city: "",
      province: "",
      orderNum: "",
      orderType: "",
      orderSource: "",
      orderState: "",
      dataTimeArr: [],
      tableData: [],
      multipleSelection: [],
      ruleForm: {},
      cityList: [],
    };
  },

  beforeCreate: function () {
    this.loading = true;
  },
  created: function () {
    this.loading = false;
    // console.log("页面初始化");
  },
  mounted: function () {
    this.fetchData();
    this.$axios({
      url: "province/findAll",
      method: "get",
    })
      .then((res) => {
        if (res.data.code == 0) {
          (this.provinceList = []),
            res.data.data.forEach((item) => {
              this.provinceList.push({ label: item.province, value: item.id });
            });
        }
      })
      .catch((err) => {
        console.log("请求错误" + err);
      });
  },
  methods: {
    // 导出
   
        daochu(){
     if (this.tableData.length < 1){
                    this.$message.error('请选择要导出的内容！');
                    return false;
                }
                this.selectWindow = true;
    },
     handleSelectionChange(val) {
                this.tableData = val;
            },
             exportExcel() {
                excel.getExcel('#selectTable','导出的自定义标题')
            },
    
    changeProvinceValue(itemid) {
      // console.log(itemid);
      this.$axios({
        url: `province/findCityByProvinceId?provinceId=${itemid}`,
      })
        .then((res) => {
          if (res.data.code == 0) {
            (this.cityList = []),
              res.data.data.forEach((item) => {
                this.cityList.push({ label: item.city, value: item.id });
              });
          }
        })
        .catch((err) => {
          console.log("请求错误" + err);
        });
    },
    //批量删除
    handleSelectionChange(val) {
      // console.log("handleSelectionChange===" + val);
      this.tableChecked = val;
      // console.log(this.tableChecked);
      this.tableChecked.forEach((item) => {
        this.ids.push(item.id);
        console.log(item);
      });
    },
    batchDelete() {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "批量删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            url: `order/deleteAll`,
            method: "get",
            params: {
              ids: this.ids.join(","),
            },
          })
            .then((res) => {
              console.log(this.ids);
              if (this.ids.length !== 0 && res.data.code === 200) {
                this.fetchData();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //单个删除
    deleteBtn(item, row) {
      // console.log(item,row);
      // console.log(row.orderNum);
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            url: `order/delete?id=${row.id}`,
            method: "get",
          })
            .then((res) => {
              if (res.data.code === 200) {
                this.fetchData();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
            })
            .catch((err) => {
              console.log("删除失败" + err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteMoreBtn(index) {
      console.log("批量删除" + index);
    },
    searchBtn() {
      this.fetchData();
    },
    //添加页面跳转
    addBtnn() {
      this.$router.push("/addOrder");
    },
    //修改页面跳转
    modifyBtn(item) {
      console.log(item);
      if (item.orderType == "验车订单") {
        this.$router.push({ name: "ExamineCarOrder", query: { id: item.id } });
      }
      if (item.orderType == "领标订单") {
        this.$router.push({ name: "lMark", query: { id: item.id } });
      }
        if (item.orderType == "异地委托函") {
        this.$router.push({ name: "offsiteDelegation", query: { id: item.id } });
      }
      if (item.orderType == "新车上牌") {
        this.$router.push({ name: "licensed", query: { id: item.id } });
      }
    },
    //订单详情页面跳转
    orderDetailSee(index, item) {
      // this.$router.push("/OrderDetail");
      console.log(index, item);
      this.$router.push({ name: "OrderDetail", query: { id: item.id } });
    },
    handleBeforeUpload(file) {
      console.log("handleBeforeUpload" + file.type);
      this.readExcel(file);
    },

    submit_form() {
      // 给后端发送请求，更新数据
      console.log("假装给后端发了个请求...");
    },
    readExcel(file) {
      // 读取表格文件
      let that = this;

      if (file === null || file === undefined) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning",
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = file.name;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          that.lists = [];
          // 从解析出来的数据中提取相应的数据
          ws.forEach((item) => {
            that.lists.push({
              username: item["用户名"],
              phone_number: item["手机号"],
            });
          });
          // 给后端发请求
          this.submit_form();
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(file);
    },

    handleCityChange(val) {
      this.city = val;
      this.fetchData();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.fetchData();
    },
    fetchData() {
      // console.log("发送请求，获取数据");
      let data = {
        page: this.page,
        limit: this.pageSize,
      };
      //表示用户根据city查询数据
      if (this.city && this.city !== "") {
        data.cityId = this.city;
      }
      if (this.orderNum && this.orderNum !== "") {
        data.orderNum = this.orderNum;
      }
      if (this.orderType && this.orderType !== "") {
        data.orderType = this.orderType;
      }
      if (this.orderSource && this.orderSource !== "") {
        data.orderOrigin = this.orderSource;
      }
      if (this.orderState && this.orderState !== "") {
        data.orderStatus = this.orderState;
      }
      if (this.dataTimeArr && this.dataTimeArr.length !== 0) {
        data.startTime = this.dataTimeArr[0];
        data.endTime = this.dataTimeArr[1];
      }

      // 向服务器发送请求获取真实数据
      this.$axios({
        url: "/order/list",
        method: "post",
        data,
      })
        .then((res) => {
          console.log("发送请求" + JSON.stringify(res));
          if (res.data.code === 0) {
            // console.log("请求成功" + res);
            this.tableData = res.data.data;
            this.count = res.data.count;
          }
        })
        .catch((err) => {
          console.log("请求错误" + err);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.orderid {
  cursor: pointer;
}

.deleteButton {
  cursor: pointer;
}

.sepBread {
  font-size: 20px;
}

// .InputSelect {
//   height: 36px;
//   color: rgba(128, 128, 128, 0.363);
//   border: 2px solid rgba(128, 128, 128, 0.137);
//   border-radius: 5px;
// }
.searchBtn {
  border-radius: 10px;
  margin-left: 10px;
}

.selectData {
  // height: 35px;
  // line-height: 35px;
  margin: 8px;
}

.secondDetail {
  margin: 10px;
}

.pagination {
  text-align: center;
}

.container {
  border: none;
  border-radius: 4px;
  background-color: #409eff;
  height: 40px;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  // padding: 0 15px;
  // min-width: 80px;
  *zoom: 1;
  color: white;
}

.upload_file {
  font-size: 20px;
  opacity: 0;
  position: absolute;
  filter: alpha(opacity=0);
  // width: 60px;
}

/deep/ .el-table__header {
  // width: 100% !important;
  width: 99.9% !important;
}

/deep/ .el-table__body {
  // width: 100% !important;
  width: 99.9% !important;
}
</style>
